'use strict'
var cryptoMO = require('crypto'); // MD5算法
var parseString = require('xml2js').parseString; // xml转js对象

function  checkCard(json, id) {
	//result.type : 0 -> 没有有效卡， 1 -> 打卡成功，2 -> 重复打卡成功 3 -> 重复打卡失败
	var cards = {
		vip:[],
		number:[]
	}, //可以用卡片
		clockInLogArr = [], //如果有打卡的情况用， 临时保存卡片
		cardStatus=false, //是否有当前场馆可用卡片
		cardList = json.cardList, //卡片列表
		clockIn = null, //最近打卡
		result = {}, // 返回值
		i = 0, //循环变量
		len = 0, //循环变量
		now = new Date().getTime(), //现在的时间戳
		interval = 300000,//5分钟间隔
		clockInLog = false //近期是否打卡
	//检测是否有卡片
	if (cardList.length == 0) return result.type = 0
	
	cardList.map(item => { 
		if (item.ntatorium == id) {
			if (item.type == "vip" && item.time.indate >= now) {
				cards.vip.push(item)
			} else if (item.type == 'number' && item.number > 0) { 
				cards.number.push(item)
			}
			return true
		}
	})
	
	//检测是否有当前场馆可用卡片	
	if (cards.vip.length  == 0 && cards.number.length  == 0 ) return result.type = 0
	//检测近期打卡记录
	if (json.clockIn.length ) {
		if (json.clockIn.timestamp <= now + interval) {
			clockIn = json.clockIn[0]
			clockInLog = false
		}
	}

	//对打卡进行处理
	if (clockInLog) {//有打卡记录
		cards.map(item => {
			if (item.number) {
				clockInLogArr.push(item)
			}
		})

		if (!clockInLogArr.length) result.type = 3
		else {
			result.type = 2
			result.card = clockInLogArr[0]
			result.time = now
		}


	} else {//没有打卡记录
		if (cards.vip.length !== 0) {
			result.card = cards.vip[0]
			
		} else {
			result.card = cards.number[0]
		}
		result.type = 1
		result.time = now
		return result
	}
}
// 生成签名
function paysignjsapi(appid,body,mch_id,nonce_str,notify_url,openid,out_trade_no,spbill_create_ip,total_fee,key) {
    var ret = {
        appid: appid,
        body: body,
        mch_id: mch_id,
        nonce_str: nonce_str,
        notify_url:notify_url,
        openid:openid,
        out_trade_no:out_trade_no,
        spbill_create_ip:spbill_create_ip,
        total_fee:total_fee,
        trade_type: 'JSAPI'
    };
    var str = raw(ret);
    str = str + '&key='+key;
    str = str.toString('utf8')

    var md5Str = cryptoMO.createHash('md5').update(str).digest('hex');
    md5Str = md5Str.toUpperCase();
    return md5Str;
}
function raw(args) {
    var keys = Object.keys(args);
    keys = keys.sort(); 
    var newArgs = {};
    keys.forEach(function(key) {
        newArgs[key.toLowerCase()] = args[key];
    });

    var str = '';
    for(var k in newArgs) {
        str += '&' + k + '=' + newArgs[k];
    }
    str = str.substr(1);
    return str;
}
function paysignjs(appid, nonceStr, packageStr, signType, timeStamp, key) {
    var ret = {
        appId: appid,
        nonceStr: nonceStr,
        package: packageStr,
        signType: signType,
        timeStamp: timeStamp
    };
    var str = raw1(ret);
    str = str + '&key='+key;
    return cryptoMO.createHash('md5').update(str).digest('hex');
}

function raw1(args) {
    var keys = Object.keys(args);
    keys = keys.sort()
    var newArgs = {};
    keys.forEach(function(key) {
        newArgs[key] = args[key];
    });

    var str = '';
    for(var k in newArgs) {
        str += '&' + k + '=' + newArgs[k];
    }
    str = str.substr(1);
    return str;
}

function getXMLNodeValue(node_name, xml) {
    var tmp = xml.split("<" + node_name + ">");
    var _tmp = tmp[1].split("</" + node_name + ">");
    return _tmp[0];
}
var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
function generateMixed(n) {
  var res = "", n = n || 32, timestamp = new Date().getTime() / 1000;
  for (var i = 0; i < n; i++) {
    var id = Math.ceil(Math.random() * 35);
    res += chars[id];
  }
  return res;
  // return res + '?' + timestamp;
}

/**
 * 将日期格式化成指定格式的字符串
 * @param date 要格式化的日期，不传时默认当前时间，也可以是一个时间戳
 * @param fmt 目标字符串格式，支持的字符有：y,M,d,q,w,H,h,m,S，默认：yyyy-MM-dd HH:mm:ss
 * @returns 返回格式化后的日期字符串
 */
function formatDate(date, fmt)
{
    date = date == undefined ? new Date() : date;
    date = typeof date == 'number' ? new Date(date) : date;
    fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
    var obj =
    {
        'y': date.getFullYear(), // 年份，注意必须用getFullYear
        'M': date.getMonth() + 1, // 月份，注意是从0-11
        'd': date.getDate(), // 日期
        'q': Math.floor((date.getMonth() + 3) / 3), // 季度
        'w': date.getDay(), // 星期，注意是0-6
        'H': date.getHours(), // 24小时制
        'h': date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, // 12小时制
        'm': date.getMinutes(), // 分钟
        's': date.getSeconds(), // 秒
        'S': date.getMilliseconds() // 毫秒
    };
    var week = ['天', '一', '二', '三', '四', '五', '六'];
    for(var i in obj)
    {
        fmt = fmt.replace(new RegExp(i+'+', 'g'), function(m)
        {
            var val = obj[i] + '';
            if(i == 'w') return (m.length > 2 ? '星期' : '周') + week[val];
            for(var j = 0, len = val.length; j < m.length - len; j++) val = '0' + val;
            return m.length == 1 ? val : val.substring(val.length - m.length);
        });
    }
    return fmt;
}
module.exports = {
	checkCard: checkCard,
	paysignjsapi: paysignjsapi,
	raw: raw,
	raw1: raw1,
	paysignjs: paysignjs,
	getXMLNodeValue: getXMLNodeValue,
	formatDate: formatDate,
	generateMixed: generateMixed
}
